package com.itheima.core.controller;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.itheima.core.pojo.user.Buyer;
import com.itheima.core.service.BuyerService;

/**
 *
 * @author zhang.cheng
 *
 *         2017年4月6日
 */
@Controller
public class LoginController {

	@Autowired
	private BuyerService buyerService;

	@RequestMapping(value = "/login.aspx", method = RequestMethod.GET)
	public String login(HttpServletRequest request, HttpServletResponse response, String returnUrl, Model model) {
		model.addAttribute("returnUrl", returnUrl);
		return "login";
	}

	@RequestMapping(value = "/login.aspx", method = RequestMethod.POST)
	public String loginToShoping(String username, String password, String returnUrl, Model model,
			HttpServletRequest request, HttpServletResponse response) {
		// 1.验证码不能为空
		// 2.验证码是否正确
		// 3.用户名不能为空
		if (StringUtils.isEmpty(username)) {
			model.addAttribute("error", "用户名不能为空!");
			return "login";
		}
		// 4.密码不能为空
		if (StringUtils.isEmpty(password)) {
			model.addAttribute("error", "密码不能为空!");
			return "login";
		}
		// 5.用户名是否存在
		Buyer buyer = buyerService.selectBuyerByUsername(username);
		if (buyer == null) {
			model.addAttribute("error", "用户名不存在!");
			return "login";
		}

		// 6.密码是否正确
		if (buyer.getPassword().equals(encodePassword(password))) {
			return "redirect:" + returnUrl;
		} else {
			model.addAttribute("error", "密码不正确!");
		}
		return "login";
	}

	// 加密
	public String encodePassword(String password) {
		// MD5 jdk
		String algorithm = "MD5";

		// password = "safqwgfh45wtb123456bntrjtrewebergntyr";

		char[] encodeHex = null;
		try {
			// 第一次加密
			MessageDigest instance = MessageDigest.getInstance(algorithm);
			byte[] digest = instance.digest(password.getBytes());
			// 第二次 Hex
			encodeHex = Hex.encodeHex(digest);
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new String(encodeHex);
	}

	//加密测试
	/*public static void main(String[] args) {
		LoginController l = new LoginController();
		String s = l.encodePassword("123456");
		System.out.println(s);
	}*/

}
